package com.elontian.http.async2.strategy.impl;

import android.graphics.Bitmap;
import android.widget.ImageView;

import com.elontian.application.CodeBoyApplicationInfo;
import com.elontian.client.BitMapCacheHelper;
import com.elontian.http.async2.modle.Response;
import com.elontian.http.async2.strategy.IAsyncStrategy;
import com.elontian.http.async2.util.HttpParams;
import com.elontian.util.CheckUtil;
import com.elontian.util.NetWork;

public class AsyncLoadImgStrategy implements IAsyncStrategy {

	private String url;
	private int width;
	private int height;
	private ImageView view;
	private Response response = new Response();;

	public AsyncLoadImgStrategy(String url, int width, int height,
			ImageView view) {
		super();
		this.url = url;
		this.width = width;
		this.height = height;
		this.view = view;
		view.setTag(url);
	}

	@Override
	public Response getResponse() throws Exception {
		// TODO Auto-generated method stub
		Bitmap bitmap = null;
		// 读取缓存文件夹中的图片
		bitmap = BitMapCacheHelper.readBitmapFromLocal(url, width, height);
		if (bitmap == null && NetWork.isNetworkConnected()) {
			// 读取网络中的图片

			bitmap = BitMapCacheHelper.readBitmapNet(url, width, height);
			savaImg(bitmap, url);

		}

		if (CheckUtil.isNotNullBitmap(bitmap)) {
			response.add(HttpParams.URL, url);
			response.add(HttpParams.IMAGEVIEW, view);
			response.add(HttpParams.RESULT, bitmap);
			response.setHavaResult(true);
		} else {
			response.setHavaResult(false);
		}

		return response;
	}

	private void savaImg(final Bitmap bitmap, final String url) {

		CodeBoyApplicationInfo.executorService.submit(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				BitMapCacheHelper.writeBitmap(url, bitmap);
			}
		});

	}

}
